package com.task.util;

import com.task.model.TaskModel;
import it.sauronsoftware.cron4j.Scheduler;
import it.sauronsoftware.cron4j.Task;
import it.sauronsoftware.cron4j.TaskExecutor;
import org.dom4j.DocumentException;

import java.util.List;


/**
 * @author carey
 * @docRoot DispatcherManager.java
 * @version 1.0
 * @see  
 * @since 
 */
public class DispatcherManager {

    private  static  Scheduler SCHEDULER;
    private  static  List<TaskModel> taskModelList;

    public static void setTaskModelList(List<TaskModel> taskModelList) {
        DispatcherManager.taskModelList = taskModelList;
    }

    static {
        SCHEDULER = new Scheduler();
    }

    /**
     * @description 获取调度器引用
     * @param
     * @date 下午4:38
     * @exception NullPointerException
     * @return 
     */
    public static Scheduler getScheduler() throws NullPointerException {
        if(null==SCHEDULER){
            throw  new NullPointerException("scheduler is null");
        }
        return SCHEDULER;
    }

    /**
     * 获取任务列表
     * @author carey
     * @date 2018/2/13 上午1:46
     * @return java.util.List<com.task.model.TaskModel>
     * @exception
     */
    public static List<TaskModel> getTaskModelList(){
        return taskModelList;
    }

    /**
     * 加载任务列表
     * @author carey
     * @date 2018/2/13 上午1:47
     * @return java.util.List<it.sauronsoftware.cron4j.Task>
     * @exception
     */
    public  static List<Task> loadTaskList(){

        Dom4jReader dom4jReader=new Dom4jReader();
        try {
            List<TaskModel> taskModels= dom4jReader.readTaskXML();


            for(TaskModel taskModel:taskModels){
                 String classPath=taskModel.getClassPath();

                try {
                    if (taskModel.getStatus().equals("run")) {
                        Runnable object = (Runnable) Class.forName(classPath).newInstance();
                        String  taskId=SCHEDULER.schedule(taskModel.getCrontab(), object);
                        taskModel.setTaskId(taskId);
                    }

                    } catch(InstantiationException e){
                        e.printStackTrace();
                    } catch(IllegalAccessException e){
                        e.printStackTrace();
                    } catch(ClassNotFoundException e){
                        e.printStackTrace();
                    }
            }

            if(null!=taskModels){
                setTaskModelList(taskModels);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }


        return null;
    }









}
